import { Computed, Mut, VueService } from "vue3-oop";
import type { FormData, WidgetType } from "./index";
import WidgetProps from "../widgets/basic/WidgetProps"

interface IWidgetNode {
  formData: FormData,
  parentId?: string | undefined,
  widgetId: string,
  widgetType: WidgetType,
  widgetProps: WidgetProps,
  children?: WidgetNode[],
}
export default class WidgetNode extends VueService implements IWidgetNode{

  @Mut() formData: FormData;
  @Mut() parentId: string | undefined;
  @Mut() widgetId: string;
  @Mut() widgetType: WidgetType;
  @Mut() widgetProps: WidgetProps;
  @Mut() children = [] as WidgetNode[];

  constructor(props:IWidgetNode) {
    super();
    this.formData = props.formData;
    this.parentId = props.parentId;
    this.widgetId = props.widgetId;
    this.widgetType = props.widgetType;
    this.widgetProps = props.widgetProps;
  }

  /** 父节点 */
  @Computed() get parentWidgetNode(){
    return this.formData.nodeMap.get(this.parentId as string);
  }

  /** 判断本节点是否选中 */
  isSelected=():boolean=>{
    return this.formData.isSelectedWidgetId(this.widgetId)
  }

  /** 设置本节点选中 */
  setSelected=():void=>{
    this.formData.setSelectedWidgetId(this.widgetId);
  }

  /** 设置父节点选中 */
  setParentSelected=():void=>{
    this.formData.setSelectedWidgetId(this.parentId as string);
  }

  /**
   * 将子节点向前移动一位
   * @param widgetId 子节点ID
   */
  moveChildNodeFoward=(widgetId:string):void=>{
    for(let i=1;i<this.children.length;i++){
      if (this.children[i].widgetId === widgetId) {
        let tmp = this.children[i - 1];
        this.children[i - 1] = this.children[i];
        this.children[i] = tmp;
        break;
      }
    }
  }

  /**
   * 将本节点向前移动一位
   */
  moveFoward=():void=>{
    this.parentWidgetNode?.moveChildNodeFoward(this.widgetId);
  }

  /**
   * 将子节点向后移动一位
   * @param widgetId 子节点ID
   */
  moveChildNodeBackwards=(widgetId:string):void=>{
    for (let i = 0; i < this.children.length - 1; i++) {
      if (this.children[i].widgetId === widgetId) {
        let tmp = this.children[i + 1];
        this.children[i + 1] = this.children[i];
        this.children[i] = tmp;
        break;
      }
    }
  }

  /**
   * 将本节点向后移动一位
   */
  moveBackwards=()=>{
    this.parentWidgetNode?.moveChildNodeBackwards(this.widgetId);
  }

  /**
   * 删除子节点
   * @param widgetId 子节点ID
   */
  removeChildNode=(widgetId:string):void=>{
    this.children = this.children.filter((childNode)=>childNode.widgetId!==widgetId);
    this.formData.nodeMap.delete(widgetId);
  }

  /**
   * 删除本节点
   */
  remove=()=>{
    this.parentWidgetNode?.removeChildNode(this.widgetId);
  }
}